package com.测试脚本引擎Rhino;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;
import java.net.URL;
import java.util.List;

/**
 * 测试脚本引擎执行javascript代码
 *
 * @author jiangbang
 * @date 2016/9/20
 */
public class Demo01 {
    public static void main(String[] args) throws ScriptException, NoSuchMethodException, FileNotFoundException {
        //获取脚本引擎对象
        ScriptEngineManager sem = new ScriptEngineManager();
        ScriptEngine engine = sem.getEngineByName("javascript");

        //定义变量,存储到引擎上下文
        engine.put("msg","good man!");
        String str = "var user = {name:'jiangbang',age:'18',schools:['大学','中学']};";
        str +="println(user.name);";

        //执行脚本
        engine.eval(str);
        //修改msg
        engine.eval("msg = 'jiangbang is a good man';");
        System.out.println(engine.get("msg"));
        System.out.println("####################");

        //定义函数
        engine.eval("function add(a,b){var sum = a+b; return sum;}");
        //执行js函数
        Invocable jsInvoke = (Invocable) engine;
        Object result1 = jsInvoke.invokeFunction("add",new Object[]{13,20});
        System.out.println(result1);
        System.out.println("####################");

        //导入其他java包，使用其他包中java类,若需要深入了解细节，可以详细学习rhino
        String jsCode = "importPackage(java.util); var list = Arrays.asList([\"北京尚学堂\",\"清华大学\",\"北京大学\"]); ";
        engine.eval(jsCode);
        List<String> list2 = (List<String>) engine.get("list");
        for (String temp : list2) {
            System.out.println(temp);
        }

        //执行一个js文件(我们将a.js至于项目的src下即可)
        URL is = Demo01.class.getClassLoader().getResource("a.js");
        Reader r = new FileReader(is.getPath());
        engine.eval(r);
    }
}
